import axios from 'axios';
import { ElMessage } from 'element-plus';

// 创建 axios 实例
const instance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 30000,
});

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers['Content-Type'] = 'application/json;charset=utf-8';
            config.headers['JwtName'] = token;
        }
        return config;
    },
    (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
    (response) => response.data,
    (error) => {
        ElMessage.error(`网络异常：${error.message}`);
        return Promise.reject(error);
    }
);

// 工具方法
const request = {
    // 原有方法保持不变
    get(url, params = {}) {
        return instance({ url, method: 'get', params });
    },
    post(url, data = {}) {
        return instance({ url, method: 'post', data });
    },
    put(url, data = {}) {
        return instance({ url, method: 'put', data });
    },
    delete(url, data = {}) {
        return instance({ url, method: 'delete', data });
    },

    chatStream(url, params = {}, callback) {
        const queryStr = Object.keys(params)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
            .join('&');
        const fullUrl = queryStr ? `${url}?${queryStr}` : url;

        const source = new EventSource(fullUrl);

        // 接收消息
        source.onmessage = (event) => {
            // 检查是否是结束标志
            if (event.data === '[DONE]') {
                callback('[DONE]');
                source.close();
            } else {
                callback(event.data);
            }
        };

        // 错误处理
        source.onerror = () => {
            source.close();
        };

        return source;  // 返回 source 对象供外部使用
    }


};

export default request;
